<?php

namespace app\api\controller\msg;

use app\admin\controller\SystemMessage;
use app\api\controller\Sms;
use app\api\model\msg\UserMsg;
use app\api\model\UserMessageModel;
use app\api\model\UserRemindMessageModel;
use app\common\controller\Api;
use app\api\model\msg\MsgModel;
use think\Db;
use think\Request;
/**
 * 系统消息、活动消息控制器
 */
class Msg extends Api{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    public function __construct(Request $request = null)
    {
        $this->Model = new MsgModel;
        parent::__construct($request);
    }

    /**
     * @return data
     * 获取消息分类最新消息
     */

    public function info()
    {
        $input = input();
        $maxTime = Db::name('user_message')->field('type,max(id) id')
            ->where(['user_id'=>$this->auth->id])
            ->group('type')
            ->select();

        foreach ($maxTime as $key => $val){
            $list[$key] = $this->Model->alias('s')
                ->field('s.*,u.show_status')
                ->join('user_message u','u.message_id=s.id')
                ->where(['u.id'=>$val['id']])
                ->select();
        }
        $this->success('请求成功',$list);
    }

    /**
     * @return data
     * 获取消息列表
     */
    public function getInfoById($limit = 10)
    {
        $input = input();
        if (empty($input['type'])){
            $this->error("参数无效");
        }
        $limit = isset($input['limit']) ? $input['limit'] : $limit;
        $userMessageModel = new UserMessageModel();
         $data = $userMessageModel->alias('u')
             ->field('s.*,u.*')
             ->join('system_message s','s.id=u.message_id')
            ->where(['u.type'=>$input['type'],'u.user_id'=>$this->auth->id])
            ->paginate($limit);
        if(empty($data))
        {
            $this->success('无数据');
        }

//        foreach ($data as &$val){
//            var_dump($val);
//            $image = append_domain($val['image']);
//            $val['image'] = $image.'4564655';
//        }
        Db::name('user_message')->where(['type'=>$input['type'],'show_status'=>0,'user_id'=>$this->auth->id])->update(['show_status'=>1,'showtime'=>time()]);

        $this->success('请求成功',$data);

    }

    /**
     * @return data
     * 获取消息内容
     */
    public function getContentById()
    {
        $input = input();
        if (empty($input['id'])){
            $this->error("参数无效");
        }
        $data = Db::name('user_message')->alias('u')
            ->field('s.*,u.show_status,u.createtime')
            ->join('system_message s','s.id=u.message_id')
            ->where(['u.id'=>$input['id']])->find();

        if(empty($data))
        {
            $this->success('无数据');
        }
//        Db::name('user_message')->where(['id'=>$input['id'],'show_status'=>0])->update(['show_status'=>1,'showtime'=>time()]);
       $this->success('请求成功',$data);
    }

    /**
     * 消息首页
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function message()
    {
        $user = $this->auth->getUser();

        //所有的系统消息
        $systems = MsgModel::where(['type'=>'admin'])->select();
        $system_es = [];$system = [];
        if(count($systems) > 0){
            //把未读的系统消息  写入一个数组
            foreach ($systems as $key=>$value){
                $systems[$key]['is_read'] = 1;
                if(!UserMsg::get(['user_id'=>$user['id'],'message_id'=>$value['id']])){
                    $value['is_read'] = 0;
                    $system_es[] = $value;
                }
            }
            //如果未读的系统消息  大于0  则取最新的
            if(count($system_es) > 0){
                $system = end($system_es);
            }else{
                $system = end($systems);
            }
        }


        //活动消息
        $acts = MsgModel::where(['type'=>'activity'])->select();
        $act_es = [];$activity = [];
        if(count($acts) > 0){
            //把未读的活动消息  写入一个数组
            foreach ($acts as $key=>$value){
                $acts[$key]['is_read'] = 1;
                if(!UserMsg::get(['user_id'=>$user['id'],'message_id'=>$value['id']])){
                    $value['is_read'] = 0;
                    $act_es[] = $value;
                }
            }
            //如果未读的活动消息  大于0  则取最新的
            if(count($act_es) > 0){
                $activity = end($act_es);
            }else{
                $activity = end($acts);
            }
        }


        //未读的提醒消息
        $reminder = UserRemindMessageModel::where(['user_id'=>$user['id'],'day'=>date('Y-m-d'),'is_read'=>0])->count();
        $this->success('获取成功',['system'=>$system,'activity'=>$activity,'remind'=>'您有'.$reminder.'条消息未读']);
    }

    /**
     * 活动消息
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function activity()
    {
        //获取用户信息
        $user = $this->auth->getUser();

        //获取分页数据
        $input = input();
        $type = $input['type'];
        $page = isset($input['page']) ? $input['page'] : 1;
        $pageSize = isset($input['pageSize']) ? $input['pageSize'] : 10;

        //查询总数  计算总页数 和查询数据
        $total = MsgModel::where(['type'=>$type])->count();
        $total_page = ceil($total/$pageSize);
        $activity = MsgModel::where(['type'=>$type])->order('id','desc')->limit(($page - 1)*$pageSize,$pageSize)->select();

        //获取已读未读状态
        foreach ($activity as $key=>$value){
            $user_msg = UserMsg::where(['user_id'=>$user['id'],'message_id'=>$value['id']])->find();
            $activity[$key]['is_read'] = $user_msg ? 1 : 0;
        }
        $this->success('获取成功',['activity'=>$activity,'current_page'=>$page,'total'=>$total,'pageSize'=>$pageSize,'total_page'=>$total_page]);
    }

    /**
     * 系统消息
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function system()
    {
        //获取用户信息
        $user = $this->auth->getUser();

        //获取分页数据
        $input = input();
        $type = $input['type'];
        $page = isset($input['page']) ? $input['page'] : 1;
        $pageSize = isset($input['pageSize']) ? $input['pageSize'] : 10;

        //查询总数  计算总页数 和查询数据
        $total = MsgModel::where(['type'=>$type])->count();
        $total_page = ceil($total/$pageSize);
        $system = MsgModel::where(['type'=>$type])->order('id','desc')->limit(($page - 1)*$pageSize,$pageSize)->select();

        //获取已读未读状态
        foreach ($system as $key=>$value){
            $user_msg = UserMsg::where(['user_id'=>$user['id'],'message_id'=>$value['id']])->find();
            $system[$key]['is_read'] = $user_msg ? 1 : 0;
        }
        $this->success('获取成功',['system'=>$system,'current_page'=>$page,'total'=>$total,'pageSize'=>$pageSize,'total_page'=>$total_page]);
    }

    /**
     * 消息详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $input = input();
        $user = $this->auth->getUser();

        //获取消息
        $message = MsgModel::get($input['id']);

        //是否已读
        $user_msg = UserMsg::where(['user_id'=>$user['id'],'message_id'=>$input['id']])->find();
        $message['is_read'] = !$user_msg ? 0 : 1;

        //添加消息已读
        if(!$user_msg){
            $user_msg = new UserMsg();
            $user_msg->save(['user_id'=>$user['id'],'message_id'=>$input['id']]);
        }

        $this->success('获取成功',$message);
    }
}
